package com.woniuxy.threadmethods;

import lombok.extern.slf4j.Slf4j;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: Blocking 模式 种植模式之两阶段终止模式
 * <P> Date: 2022/4/6:19:03
 * <P> Description:
 */
@Slf4j(topic = "c.Test13Volatile")
public class Test13Volatile {
    static volatile Object object = new Object();

    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination1 tpt = new TwoPhaseTermination1();
        tpt.start();
        tpt.start();
        tpt.start();

        Thread.sleep(3500);
        tpt.stop();
    }
}

@Slf4j(topic = "c.TwoPhaseTermination")
@SuppressWarnings("all")
class TwoPhaseTermination1 {
    /**
     * TODO 监控线程
     */
    private Thread monitor;

    private volatile boolean flag;

    private boolean starting = false;

    /**
     * TODO:启动监控现场
     **/
    public void start() {
        synchronized (this) {
            if (starting) {
                return;
            }
            starting = true;
        }
        monitor = new Thread(() -> {
            while (true) {
                if (flag) {
                    log.debug("被打断，结束循环");
                    break;
                }
                try {
                    Thread.sleep(1000);
                    log.debug("执行监控");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        monitor.start();
    }

    public void stop() {
        if (monitor != null) {
            flag = true;
        }
    }
}
